<template>
  <div class="assignment-header">
    <button class="back-button" @click="$router.go(-1)"><img src="@/assets/svgs/left.svg" alt="Back" /></button>
    <div class="information">教师签到界面</div>
    <div class="user-info" @click="toggleDropdown">
      <img class="avatar" :src="userInfo?.avatarUrl" alt="User Avatar">
      <span class="username">{{ userInfo?.nick_name }}</span>
      <img class="dropdown-arrow" src="@/assets/svgs/downnarrow.svg" alt="Dropdown Arrow">
      <div v-if="dropdownVisible" class="dropdown-menu">
        <p @click="$router.push('/teacher/information')">个人信息</p>
        <p @click="$router.push('/login')">退出登录</p>
      </div>
    </div>
  </div>
  <div class="sign-container">
    <!-- 当前签到区域 -->
    <div class="current-sign">
   <div class="sign-controls">
        <div class="input-group">
          <input v-model="duration" type="number" placeholder="输入签到时长（分钟）" class="signininput" />
          <div class="button-group">
            <button @click="startSign" class="signinbutton action-btn">发起签到</button>
            <button v-if="isCounting" @click="endSign" class="signinbutton end-btn">结束签到</button>
          </div>
        </div>

        <div class="sign-info">
          <span>生成签到码 : {{ sign.signCode }}</span>
          <span v-if="isCounting" class="timer">剩余时间: {{ remainingMinutes }} 分 {{ remainingSeconds }} 秒</span>
        </div>
      </div>
      <div class="stats-box">
        <h2>当前签到记录</h2>
        <div class="stats-grid">
          <div class="stat-item"><span>签到次数:</span> 第{{ sign.signOrder }}次</div>
          <div class="stat-item"><span>总人数:</span> {{ signStatus.total }}</div>
          <div class="stat-item"><span>已签到:</span> {{ signStatus.signed }}</div>
          <div class="stat-item"><span>签到率:</span> {{ signStatus.signInRate }}%</div>
          <div class="stat-item"><span>未签到人数:</span> {{ signStatus.total2 }}</div>
        </div>
        <div class="student-list">
          <p class="list-title">已签到学生:</p>
          <p class="list-content">{{signStatus.students.filter(s => s.status === 1).map(s => s.username).join(', ') ||
            '无'}}</p>
          <p class="list-title">未签到学生:</p>
          <p class="list-content">{{ signStatus.unSignedStudents.join(', ') || '无' }}</p>
        </div>
      </div>
   
    </div>

    <!-- 历史签到区域 -->
    <div class="history-sign">
      <div class="history-controls">
        <input type="number" v-model="Order" class="signininput" placeholder="输入查看次数">
        <button @click="handleSubmit" class="signinbutton history-btn">查看记录</button>
      </div>

      <div v-if="signStatus2.students.length > 0" class="stats-box history-stats">
        <h2>第{{ Order }}次签到记录</h2>
        <div class="stats-grid">
          <div class="stat-item"><span>总人数:</span> {{ signStatus2.total }}</div>
          <div class="stat-item"><span>已签到:</span> {{ signStatus2.signed }}</div>
          <div class="stat-item"><span>签到率:</span> {{ signStatus2.signInRate }}%</div>
          <div class="stat-item"><span>未签到人数:</span> {{ signStatus2.total2 }}</div>
        </div>
        <div class="student-list">
          <p class="list-title">已签到学生:</p>
          <p class="list-content">{{signStatus2.students.filter(s => s.status === 1).map(s => s.username).join(', ')}}
          </p>
          <p class="list-title">未签到学生:</p>
          <p class="list-content">{{ signStatus2.unSignedStudents.join(', ') }}</p>
        </div>
      </div>
    </div>
  </div>
</template>



<script setup>
import { ref } from 'vue';
import { createSign, getStatus } from '@/api/sign';
import { ElMessage,ElMessageBox } from 'element-plus'; // 确保你已经引入了 ElMessage
import { useSignOrderStore } from '@/stores/signOrder'
import { useSignIdStore } from '@/stores/signId'
import { informationService } from '@/api/personnal-information';
// 定义响应式数据

const userInfo = ref(null);

const fetchUserInfo = async () => {
    try {
        const result = await informationService();
        const userData = result.data; // 假设后端返回的数据结构是 { data: SysUser }
        userInfo.value = {
            userId: userData.userId,
            avatarUrl: userData.avatar,
            user_name: userData.userName,
            nick_name: userData.nickName
        };
    } catch (error) {
        console.error('获取用户信息失败:', result.message);
    }
};
fetchUserInfo();

const signOrderStore = useSignOrderStore();
const signIdStore = useSignIdStore();
const duration = ref(''); // 输入的签到时长（分钟）
const remainingTime = ref(0); // 剩余时间（秒）
const isCounting = ref(false); // 是否正在倒计时
const remainingMinutes = ref(0); // 剩余分钟数
const remainingSeconds = ref(0); // 剩余秒数
const signStatus = ref({// 签到记录
  total: 0,
  signed: 0,
  students: [],
  total2: 0,
  unSignedStudents: []
});
const signStatus2 = ref({// 签到历史记录
  total: 0,
  signed: 0,
  students: [],
  total2: 0,
  unSignedStudents: []
});

// 新增 AbortController 用于取消请求
const abortController = ref(null);
const sign = ref({}); // 改为对象
const Order = ref('')//签到order
let timer = null; // 定时器
let statusTimer = null; // 签到状态定时器
// 新增 dropdownVisible 响应式变量
const dropdownVisible = ref(false);
// 更新分和秒显示的方法
const updateRemainingDisplay = () => {
  remainingMinutes.value = Math.floor(remainingTime.value / 60);
  remainingSeconds.value = remainingTime.value % 60;
};
// 新增 toggleDropdown 方法
const toggleDropdown = () => {
  dropdownVisible.value = !dropdownVisible.value;
};

// 修改后的长轮询方法
const longPollStatus = async (signId) => {
  abortController.value = new AbortController();

  const poll = async () => {
    try {
      const res = await getStatus(signId, {
        signal: abortController.value.signal
      });
      signStatus.value = res;

      // 仅在倒计时期间继续轮询
      if (isCounting.value) {
        poll();
      }
    } catch (error) {
      if (error.name !== 'AbortError') {
        console.error('长轮询错误:', error);
        // 错误后延迟 1 秒重试
        setTimeout(poll, 1000);
      }
    }
  };

  poll();
};
//增加结束签到方法
const endSign = () => {
  clearInterval(timer);
  clearInterval(statusTimer);
  if (abortController.value) {
    abortController.value.abort();
  }
  isCounting.value = false;
  remainingTime.value = 0;
  ElMessage.success('已结束当前签到');
};
// 发起签到的方法

const startSign = async () => {
  if (isCounting.value) {
    try {
      await ElMessageBox.confirm('检测到有进行中的签到，是否结束当前签到并开始新的？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      this.endSign();
    } catch {
      return;
    }
  }
  const inputValue = Number(duration.value);
  if (!inputValue || inputValue < 1 || inputValue > 20) {
    ElMessage.warning('请输入1-20之间的整数');
    return;
  }
  // 将分钟转换为秒
  remainingTime.value = inputValue * 60;
  isCounting.value = true;
  // 更新初始的分和秒显示
  updateRemainingDisplay();
  // 启动倒计时
  timer = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--;
      updateRemainingDisplay();
    } else {
      // 倒计时结束
      clearInterval(timer);
      clearInterval(statusTimer); // 停止签到状态定时器
      isCounting.value = false;
    }
  }, 1000);//一秒更新一次

  try {
    const response = await createSign(duration.value);
    sign.value = response;
    const n = response.signId;

    if (n) {
      // 停止之前的轮询
      if (abortController.value) {
        abortController.value.abort();
      }
      longPollStatus(n);
    }
  } catch (error) {
    ElMessage.error('发起签到失败');
    console.error('2发起签到失败:', error);
  }
};


const handleSubmit = async () => {
  const signId = signIdStore.signId;
  console.log('已从Store获取signId:', signId);
  const signOrder = signOrderStore.signOrder;
  const inputOrder = Number(Order.value);
  if (isNaN(inputOrder) || inputOrder <= 0) {
    ElMessage.warning('请输入有效的整数');
    return;
  }
  if (inputOrder > signOrder) {
    ElMessage.warning('请输入小于等于当前签到次数的数字');
    return;
  }
  try {
    const num = signId - signOrder + inputOrder;
    const res = await getStatus(num);
    signStatus2.value = res;
  }
  catch (error) {
    console.error('获取历史状态失败:', error);
    ElMessage.error('获取签到状态失败');
  }
};
</script>

<style scoped>
.assignment-header {
  display: flex;
  height: 7lvh;
  width: 99lvw;
  background-color: #13227A;
  color: white;
}

.back-button {
  background-color: transparent;
  width: 3%;
  color: white;
  cursor: pointer;
}

.information {
  margin-left: 37.5%;
  font-size: 28px;
  line-height: 7lvh;
  font-family: kaiti;
  color: rgb(243, 245, 254);
}

.user-info {
  position: relative;
  align-items: center;
  cursor: pointer;
  display: flex;
  margin-left: 39%;
  z-index: 999;
}

.avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 10px;
}

.dropdown-arrow {
  width: 16px;
  height: 16px;
  margin-left: 5px;
}

.username {
  font-size: 16px;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background-color: white;
  color: black;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 10px;
  z-index: 1000;
}

.dropdown-menu :hover {
  background-color: #f0f0f0;
  color: brown;
}

.siinput {
  width: 98lvw;
  margin-top: 3lvh;
  height: 18lvh;
}

.signininput {
  float: left;
  width: 40%;
  margin-left: 10%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  height: 3.4lvh;
}

.signinbutton {
  display: inline-block;
  margin-left: 1lvw;
  width: 7lvw;
  height: 5.7lvh;
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.signinbutton:hover {
  background-color: #0056b3;
}

.sign-container {
  width: 98lvw;
  height: 85lvh;
  margin-top: 0.2lvh;
  display: flex;
  flex-direction: row;
}

.current-sign {
  background: #f8f9fa;
  width: 40%;
  height: 89lvh;
  max-height: 89lvh;
  overflow-y: auto;
  margin-left: 5%;
  padding-left: 20px;
  padding-right: 20px;
  padding-top: 10px;
  border-radius: 2%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.history-sign {
  background: #fff;
  padding: 20px;
  width: 40%;
  height: 85lvh;
  max-height: 85lvh;
  margin-left: 4%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.sign-controls {
  height: 20%;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 2lvh;
}

.input-group {
  display: flex;
  flex-direction: row;
  width: 100%;
}

.button-group {
  display: flex;
  gap: 10px;
}




.signinbutton {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn {
  background: #007bff;
  color: white;
}

.end-btn {
  background: #dc3545;
  color: white;
}

.history-btn {
  background: #28a745;
  color: white;
}

.sign-info {
  background: #f2f2f2;
  padding-left: 10%;
  border-radius: 4px;
  font-family: kaiti;
  font-size: 22px;
  line-height: 10lvh;
  height: 10lvh;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.timer {
  color: #dc3545;
  font-weight: bold;
  margin-left: 6%;
}

.stats-box {
  background: white;
  padding: 20px;
  border-radius: 8px;
  height: 63lvh;
  max-height: 63lvh;
  overflow-y: auto;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin: 15px 0;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
}

.stat-item span {
  color: #6c757d;
}

.student-list {
  margin-top: 15px;
}

.list-title {
  font-weight: 600;
  color: #343a40;
  margin: 8px 0;
}

.list-content {
  background: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  color: #495057;
}
</style>